package com.app.island.cash.requestview

import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.app.island.cash.databinding.RenzhengKanpainActBinding
import com.app.island.cash.data.sigle.CardInfoDataCall
import com.app.island.cash.data.sigle.FaceLiveRequest
import com.app.island.cash.data.sigle.SaveOcrCall
import com.app.island.cash.data.sigle.CardInfoBack
import com.app.island.cash.params.AppParams
import com.app.island.cash.requestwork.*
import com.app.island.cash.utilstools.NetWorkLoadingUtil
import com.app.island.cash.utilstools.SystemUtils
import com.app.island.cash.utilstools.ToastUtil
import com.app.island.cash.utilstools.UserInfoManager
import com.google.gson.Gson
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.net.URLDecoder
import java.util.*

class Renzheng1HttpUtil(context:AppCompatActivity,binding: RenzhengKanpainActBinding) {
    fun huoqukapianxinxi(requestCode:Int,cardInfoDataCall: CardInfoDataCall) {
        val map: Map<String, Any> = getFieldVlaue(cardInfoDataCall)
        var tree: TreeMap<String, Any> = TreeMap(map)
        tree = dynamicParams(tree)
        val temp: TreeMap<*, *> = TreeMap<Any?, Any?>(tree)
        val head: MutableMap<String, String> = HashMap()
        head["token"] = UserInfoManager.instance.token
        head["signMsg"] = getSign(temp)
        NetWorkLoadingUtil.showDialog(context)
        NetImageClient.getService(
            AppService::class.java
        ).imageScan(head, getRequestMap(tree)).enqueue(object : RequestCallBack<HttpResult<CardInfoBack>?>() {
            override fun onSuccess(body: HttpResult<CardInfoBack>?) {
                when (requestCode) {
                    1010 -> {
                        shezhizhengmian(body?.data,cardInfoDataCall)
                    }
                    1011 -> {
                        shezhifanmian(body?.data,cardInfoDataCall)
                    }
                    else -> {
                        shezhishuika(body?.data,cardInfoDataCall)
                    }
                }
            }
        })
    }
    var shuikaStr:String?=null
    var shuikaPathStr:String?=null
    private fun shezhishuika(data: CardInfoBack?, cardInfoDataCall: CardInfoDataCall) {
        data?.let {
            shuikaPathStr = cardInfoDataCall.image.absolutePath
            shuikaStr = Gson().toJson(data)
            binding.panNo.text = it.idNumber
            binding.birth.text = it.birthday
            Glide.with(context).load(cardInfoDataCall.image).into(binding.ivPan)
        }
    }

    var fanmianStr:String?=null
    var fanmianPathStr:String?=null
    private fun shezhifanmian(data: CardInfoBack?, cardInfoDataCall: CardInfoDataCall) {
        data?.let {
            fanmianPathStr = cardInfoDataCall.image.absolutePath
            fanmianStr = Gson().toJson(data)
            binding.pinCode.text = it.pin
            binding.address.text = it.addressAll
            Glide.with(context).load(cardInfoDataCall.image).into(binding.ivBack)
        }
    }

    fun getRequestMap(map: Map<String, Any>): Map<String, @JvmSuppressWildcards RequestBody> {
        val params: MutableMap<String, RequestBody> = HashMap()
        for ((key, value) in map) {
            if (TextUtils.isEmpty(key) || null == value) {
                continue
            }
            if (value is File) {
                val file = value
                params[key.toString() + "\"; filename=\"" + file.name + ""] =
                    RequestBody.create(MultipartBody.FORM, file)
            } else {
                params[key as String] = RequestBody.create(
                    MultipartBody.FORM,
                    (value as String?)!!
                )
            }
        }
        return params
    }

    var zhemgianStr:String?=null
    var zhemgianPathStr:String?=null
    private fun shezhizhengmian(data: CardInfoBack?, cardInfoDataCall: CardInfoDataCall) {
        data?.let {
            zhemgianPathStr = cardInfoDataCall.image.absolutePath
            zhemgianStr = Gson().toJson(data)
            binding.gender.text = it.gender
            binding.name.text = it.name
            binding.adNo.text = it.idNumber
            Glide.with(context).load(cardInfoDataCall.image).into(binding.ivFront)
        }
    }

    private fun getSign(map: TreeMap<*, *>): String {
        var signa = ""
        try {
            val it: Iterator<*> = map.entries.iterator()
            val sb = StringBuilder()
            while (it.hasNext()) {
                val entry = it.next() as Map.Entry<*, *>
                if (entry.value is File) continue  //URLEncoder.encode(, "UTF-8")
                sb.append(entry.key).append("=")
                    .append(URLDecoder.decode(entry.value.toString(), "UTF-8")).append("|")
            }
            // 所有请求参数排序后的字符串后进行MD5（32）
            //signa = MDUtil.encode(MDUtil.TYPE.MD5, sb.toString());
            // 得到的MD5串拼接appsecret再次MD5，所得结果转大写
            var sign = ""
            sign = if (sb.toString().length > 1) {
                sb.toString().substring(0, sb.length - 1)
            } else {
                sb.toString()
            }
            signa =
                SystemUtils.encode(AppParams.SIGN_KEY + UserInfoManager.instance.token + sign).toUpperCase()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return signa
    }

    fun dynamicParams(map: TreeMap<String, Any>): TreeMap<String, Any> {
        map["mobileType"] = "2"
        map["versionNumber"] = SystemUtils.versionName
        map["appFlag"] = AppParams.flag
        map["client"] = "Android"
        map["channelCode"] = AppParams.channel
        val token = UserInfoManager.instance.token
        val userId = UserInfoManager.instance.uid
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(userId)) {
            map["token"] = token
            map["userId"] = userId
        }
        return map
    }

    private val context:AppCompatActivity = context
    private val binding:RenzhengKanpainActBinding = binding
    private fun getFieldVlaue(obj: Any): MutableMap<String, Any> {
        val mapValue: MutableMap<String, Any> = HashMap()
        val cls: Class<*> = obj.javaClass
        val fields = cls.declaredFields
        try {
            for (field in fields) {
                val name = field.name
                val strGet =
                    "get" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length)
                val methodGet = cls.getDeclaredMethod(strGet)
                val `object` = methodGet.invoke(obj)
                val value = `object` ?: ""
                mapValue[name] = value
            }
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        return mapValue
    }

    private var renlian:String?=null
    fun chaxunshifouyizhi(renlian:String?) {
        if (zhemgianPathStr.isNullOrEmpty()|| fanmianPathStr.isNullOrEmpty() || shuikaPathStr.isNullOrEmpty() || renlian.isNullOrEmpty()) {
            ToastUtil.toast("Please scan your card or first")
            return
        }
        this.renlian = renlian
        NetWorkLoadingUtil.showDialog(context)
        val request = FaceLiveRequest(File(zhemgianPathStr), File(renlian), File(shuikaPathStr))
        val map: Map<String, Any> = getFieldVlaue(request)
        var tree: TreeMap<String, Any> = TreeMap(map)
        tree = dynamicParams(tree)
        val temp: TreeMap<*, *> = TreeMap<Any?, Any?>(tree)
        val head: MutableMap<String, String> = HashMap()
        head["token"] = UserInfoManager.instance.token
        head["signMsg"] = getSign(temp)
        NetImageClient.getService(
            AppService::class.java
        ).faceTure(head, getRequestMap(tree)).enqueue(object : RequestCallBack<HttpResult<CardInfoBack>?>() {
            override fun onSuccess(body: HttpResult<CardInfoBack>?) {
                baocunxinxi()
            }
        })
    }

    private fun baocunxinxi() {
        val call = SaveOcrCall()
        call.frontImg = File(zhemgianPathStr)
        call.backImg = File(fanmianPathStr)
        call.panImg = File(shuikaPathStr)
        call.livingImg = File(renlian)
        call.realName = binding.name.text.toString()
        call.idNo = binding.adNo.text.toString()
        call.dateOfBirth = binding.birth.text.toString()
        call.gender = binding.gender.text.toString()
        call.pinCode = binding.pinCode.text.toString()
        call.idAddr = binding.address.text.toString()
        call.panCode = binding.panNo.text.toString()
        call.adFrontJson = zhemgianStr
        call.adBackJson = fanmianStr
        call.panJson = shuikaStr
        val map: Map<String, Any> = getFieldVlaue(call)
        var tree: TreeMap<String, Any> = TreeMap(map)
        tree = dynamicParams(tree)
        val temp: TreeMap<*, *> = TreeMap<Any?, Any?>(tree)
        val head: MutableMap<String, String> = HashMap()
        head["token"] = UserInfoManager.instance.token
        head["signMsg"] = getSign(temp)
        NetWorkLoadingUtil.showDialog(context)
        NetImageClient.getService(
            AppService::class.java
        ).saveNameAuthSave(head, getRequestMap(tree)).enqueue(object : RequestCallBack<HttpResult<Any>?>() {
           override fun onSuccess(body: HttpResult<Any>?) {
                ToastUtil.toast(body?.msg)
                context.finish()
            }
        })
    }

}